import axios from 'axios'
export default {
  data () {
    return {
      tableData: [],
      pagenum: 1,
      total: 0,
      pagesize: 2,
      searchText: '',
      dialogFormVisible: false,
      dialogFormEditVisible: false,
      addForm: {
        username: 'admin1',
        password: '123464',
        email: 'www.baidu.com',
        mobile: '12343566712'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '用户名长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          /* eslint-disable no-useless-escape */
          { Pattern: /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/, message: '请输入邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { Pattern: /^1(3[0-9]|5[189]|8[6789])[0-9]{8}$/, message: '请输入手机号码', trigger: 'blur' }
        ]
      },
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      isShowAssignUserDialog: false,
      assginRolesForm: {
        username: '',
        id: '',
        rid: ''
      },
      getList: []
    }
  },
  created () {
    this.renderList()
    this.getList2()
  },
  methods: {
    async renderList (pagenum = 1, query = '') {
      const res = await axios.get('http://localhost:8888/api/private/v1/users', {
        params: {
          query, // 查询参数，可以为空
          pagenum, // 当前页码，不能为空
          pagesize: 2
        },
        // 需要授权的 API ，必须在请求头中使用 Authorization 字段提供 token 令牌
        headers: {
          Authorization: localStorage.getItem('token')
        }
      })
      console.log(res.data) // msg: "无效token", status: 401
      if (res.data.meta.status === 200) {
        this.tableData = res.data.data.users
        this.pagenum = res.data.data.pagenum
        this.total = res.data.data.total
      } else {
        this.$router.push('/login')
        localStorage.removeItem('token')
      }
    },
    currentChange (curPage) {
      this.renderList(curPage, this.searchText)
    },
    btnSearch () {
      this.renderList(1, this.searchText)
    },
    async delUser (id) {
      // console.log(id)
      // alert(1)
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await this.$http.delete(`/users/${id}`)
        console.log(res.data)// msg: "无效token" status: 401
        if (res.data.meta.status === 200) {
          this.renderList()
        }
        this.$message({
          type: 'success',
          message: res.data.meta.msg
        })
      } catch (err) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      // .then(() => {
      //   // 删除成功的时候，从新渲染页面
      //   const res = await this.$http.delete(`http://localhost:8888/api/private/v1/users/${id}`).then(res => {

      //   })
      //   this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      //   })
      // }).catch(() => {

      // })
    },
    async changSwitch (curUser) {
      // console.log(curUser)
      // uId用户 ID,不能为空携带在url中
      // type用户状态,不能为空携带在url中，值为 true 或者 false
      const res = await this.$http.put(`users/${curUser.id}/state/${curUser.mg_state}`)
      // console.log(res.data)
      this.renderList(1, this.searchText)
      this.$message({
        type: 'success',
        message: res.data.meta.msg
      })
    },
    addUser () {
      // 点击添加用户，弹出对话框，修改表单信息，点击确认，从新渲染页面
      this.dialogFormVisible = true
    },
    async submitAddForm () {
      // 获取表单信息，发送请求，渲染页面
      // console.log(this.addForm)
      try {
        // await this.$refs.addFormRef.validate()
        const res = await this.$http.post('/users', this.addForm)
        console.log(res.data)
        if (res.data.meta.status === 201) {
          // 添加成功
          this.dialogFormVisible = false
          this.renderList()
          this.$message({
            type: 'success',
            message: res.data.meta.msg
          })
        }
      } catch (e) {
        console.log('添加失败')
      }
    },
    showEditDialog (curUser) {
      // 展示编辑对话框// 将原信息添加到页面上
      this.dialogFormEditVisible = true
      // console.log(curUser)
      for (let key in this.editForm) {
        this.editForm[key] = curUser[key]
      }
    },
    async editUser () {
    //  获取表单信息进行提交
      const {email, mobile} = this.editForm
      const res = await this.$http.put(`users/${this.editForm.id}`, {
        email,
        mobile
      })
      console.log(res.data)
      if (res.data.meta.status === 200) {
        // 提交成功
        this.dialogFormEditVisible = false
        // 重新渲染页面
        this.renderList(1, this.searchText)
        // 显示成功信息
        this.$message({
          type: 'success',
          message: res.data.meta.msg
        })
      }
    },
    showAssignUserDialog (curUser) {
      console.log(curUser)
      this.isShowAssignUserDialog = true
    },
    async getList2 () {
      const res = await this.$http.get('roles')
      console.log(res)
    },
    async AssignUser () {
      // const res = await this.$http.put(`users/${this.id}/role`, {
      //   // params: this.rid
      // })
      // console.log(res)
    }
  }
}
